﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ECGConversion;
using ECGConversion.ECGLeadMeasurements;
using ECGConversion.ECGSignals;
using System.Linq;


namespace HnECGConverter
{
    internal   class Program
    {
		private int _Zoom = 1;
		private int _OffsetX = 0;
		private int _OffsetY = 0;
		private int _PrevX = 0;
		private int _PrevY = 0;
		private int _LineX1 = int.MinValue;
		private int _LineX2 = int.MinValue;
		private int _LineY1 = int.MinValue;
		private int _LineY2 = int.MinValue;
		private bool _RightMouseButton = false;
		private Signals _CurrentSignal;
		private Bitmap DrawBuffer
		{
			get
			{
				lock (this)
				{
					return _DrawBuffer;
				}
			}
			set
			{
				lock (this)
				{
					if (_DrawBuffer != null)
						_DrawBuffer.Dispose();

					_DrawBuffer = value;
				}
			}
		}
		private Bitmap _DrawBuffer = null;

		private IECGFormat _CurrentECG = null;
	 	private IECGFormat CurrentECG
		{
			get
			{
				lock (this)
				{
					return _CurrentECG;
				}
			}
			set
			{
				lock (this)
				{
					_Zoom = 1;

					_OffsetX = 0;
					_OffsetY = 0;

					if ((_CurrentECG != null)
					&& (_CurrentECG != value))
						_CurrentECG.Dispose();

					if (value == null)
					{
						if (_CurrentECG != null)
							_CurrentECG.Dispose();

						_CurrentECG = null;
					}
					else
					{
						_CurrentECG = value;

						if (_CurrentECG.Signals.getSignals(out _CurrentSignal) != 0)
						{
							//this.statusBar.Text = "Failed to get signal!";

							_CurrentECG.Dispose();
							_CurrentECG = null;
						}
						else
						{
							if (_CurrentSignal != null)
							{
								for (int i = 0, e = _CurrentSignal.NrLeads; i < e; i++)
								{
									ECGTool.NormalizeSignal(_CurrentSignal[i].Rhythm, _CurrentSignal.RhythmSamplesPerSecond);
								}
							}

							Signals sig = _CurrentSignal.CalculateTwelveLeads();
							if (sig == null)
								sig = _CurrentSignal.CalculateFifteenLeads();

							if (sig != null)
								_CurrentSignal = sig;

							if (_CurrentSignal.IsBuffered)
							{
								BufferedSignals bs = _CurrentSignal.AsBufferedSignals;

								bs.LoadSignal(bs.RealRhythmStart, bs.RealRhythmStart + 60 * bs.RhythmSamplesPerSecond);
 
							}
							else
							{
								int start, end;

								_CurrentSignal.CalculateStartAndEnd(out start, out end);
 
							}
						}

						ECGDraw.ECGDrawType dt = ECGDraw.PossibleDrawTypes(_CurrentSignal);

					  
					}

					//_DrawBuffer = null;
				}
			}
		}

	static	void Main1(string[] args)
        {

			PatientInfo patientInfo = null;
			if (args.Length<1)
			{
				MessageBox.Show("没有输入参数 ，请输入需要转换的 json文件！");
			}
			string path = args[0];
			if (!File.Exists(path))
			{
				MessageBox.Show("输 json文件,不存在，请先生成！");
				path = "temp.json";

			}
			else
			{

                //读取json数据转换成对象
				patientInfo= JsonHelper.DeserializeFileToObject<PatientInfo>(path);
				 
			}

            try
            {
				IECGFormat CurrentECG=null;
				UnknownECGReader _ECGReader = null;
                if (true)
                {
                    int index = 0;
					if (_ECGReader == null)
						_ECGReader = new UnknownECGReader();
					CurrentECG = _ECGReader.Read("Example.xml");
					//需要在此处 给 CurrentECG  赋值 
					//读取 json文件中的 数据，赋值CurrentECG
					int leadCount = patientInfo.ChDatas.Count;
					Signal[] _sign = new Signal[leadCount];
					for (int i=0;i<leadCount;i++)
					{
						_sign[i] = new Signal();
						try
                        {
							string leadname = patientInfo.ChDatas[i].LeadName.Trim();
							// 导联类型
							_sign[i].Type = (LeadType)(LeadTypeVitalRefId)ECGConverter.EnumParse(
								 typeof(LeadTypeVitalRefId), leadname, true);
							//导联数据 ，
							string[] datastr = patientInfo.ChDatas[i].digital.TrimEnd().Split(' ');
							short[] shortArray = Array.ConvertAll<string, short>(datastr, delegate (string s) { return (short)(float.Parse(s) * 10000);  });
							_sign[i].Rhythm = (short[])shortArray.Clone();
							_sign[i].RhythmStart = 0;
							_sign[i].RhythmEnd = shortArray.Length / 500;
						}
						catch (Exception ex)
                        {
                            throw;
                        }
					}

					Signals signals = new Signals();
					signals.SetLeads(_sign);
					CurrentECG.Signals.getSignals(out signals);
					//采样率
					signals.RhythmSamplesPerSecond =int.Parse( patientInfo.Increament);
					//增益 
					signals.RhythmAVM = int.Parse(patientInfo.ChDatas[1].Sacle);
					//在这里设置参数信息 
					//setLeadMeasurements
					//设置导联参数 
					LeadMeasurements leadMeasurements;
					//CurrentECG.LeadMeasurements.getLeadMeasurements(out leadMeasurements);
					//这里补充参数
					//CurrentECG.LeadMeasurements.setLeadMeasurements(leadMeasurements);
                     
                    //setGlobalMeasurements 总分析参数
                    ECGConversion.ECGGlobalMeasurements.GlobalMeasurements globalMeasurements = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
					CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);
                    //ECGConversion.ECGGlobalMeasurements.GlobalMeasurements glob = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                    globalMeasurements.Pdur = 120;
                    globalMeasurements.QTc = 220;
                    //12个 导联的信息 
                    //ECGConversion.ECGGlobalMeasurements. GlobalMeasurement[] gment=new ECGConversion.ECGGlobalMeasurements.GlobalMeasurement[12];
                   // glob.measurment = gment;
                    CurrentECG.GlobalMeasurements.setGlobalMeasurements(globalMeasurements);
					CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);

					ECGConversion.ECGDiagnostic.Statements stat;
					CurrentECG.Diagnostics.getDiagnosticStatements(out stat);

					int NrConfigItems= CurrentECG.Config.NrConfigItems  ;

					//ECGConversion.aECG.aECGControlVariableHolder aECGControl;

					//IECGFormat ret = new ECGConversion.aECG.aECGFormat();

					ECGConversion.aECG.aECGFormat eCGFormat = (ECGConversion.aECG.aECGFormat)CurrentECG;

					ECGConversion.aECG.aECGComponent aECGComponent = eCGFormat.Component;

                    //ECGConversion.aECG.aECGControlVariable[] controlVarible = eCGFormat.ControlVariables;
                    
				 
					//这里设置 患者信息
					CurrentECG.Demographics.FirstName =patientInfo.Name;
					//
					CurrentECG.Demographics.Gender =(ECGConversion.ECGDemographics.Sex) int.Parse(patientInfo.Sex);
					//身高
					ushort height = ushort.Parse(patientInfo.Height);
					CurrentECG.Demographics.setPatientHeight(height, ECGConversion.ECGDemographics.HeightDefinition.Millimeters);
					ushort weight = ushort.Parse(patientInfo.Weight);
					CurrentECG.Demographics.setPatientWeight(weight, ECGConversion.ECGDemographics.WeightDefinition.Kilogram);

					ushort age = ushort.Parse(patientInfo.Age);
					ECGConversion.ECGDemographics.AgeDefinition ageuint = ECGConversion.ECGDemographics.AgeDefinition.Unspecified;
					if (patientInfo.Ageuint == "岁")
					{
						ageuint = ECGConversion.ECGDemographics.AgeDefinition.Years;
					}
					else if (patientInfo.Ageuint == "月")
					{
						ageuint = ECGConversion.ECGDemographics.AgeDefinition.Months;
					}
					else if (patientInfo.Ageuint == "天")
					{
						ageuint = ECGConversion.ECGDemographics.AgeDefinition.Days;
					}
					else if (patientInfo.Ageuint == "周")
					{
						ageuint = ECGConversion.ECGDemographics.AgeDefinition.Weeks;
					}
					CurrentECG.Demographics.setPatientAge(age, ageuint);


					IECGFormat writeFile = CurrentECG;
	
					if (index >= 0)
                    {
                        ECGConfig cfg1 = ECGConverter.Instance.getConfig(index);

                        if (cfg1 != null)
                        {
                            cfg1["Lead Format"] = "Regular";
                            cfg1["Gain"] = "10";
                        }

                        try
                        {
                            if (CurrentECG.GetType() != ECGConverter.Instance.getType(index))
							{
								if (((ECGConverter.Instance.Convert(CurrentECG, index, cfg1, out writeFile) != 0)
								|| !writeFile.Works())
								&& (writeFile != null))
								{
									writeFile.Dispose();
									writeFile = null;
								}
                            }
                        }
                        catch
                        {
                            if (writeFile != null)
                            {
                                writeFile.Dispose();
                                writeFile = null;
                            }
                        }

                        if (writeFile == null)
                        {
                            //MessageBox.Show(this, "Converting of file has failed!", "Converting failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    ECGWriter.Write(writeFile, "test.xml", true);

                    if (writeFile != CurrentECG)
                        writeFile.Dispose();

                    if (ECGWriter.getLastError() != 0)
                    {
                        //MessageBox.Show(this, ECGWriter.getLastErrorMessage(), "Writing of file failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(this, ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    static void Main(string[] args)
    {

        PatientInfo patientInfo = null;
        if (args.Length < 1)
        {
            MessageBox.Show("没有输入参数 ，请输入需要转换的 json文件！");
        }
        string path = args[0];
        if (!File.Exists(path))
        {
            MessageBox.Show("输 json文件,不存在，请先生成！");
            path = "temp.json";

        }
       
            //读取json数据转换成对象
            patientInfo = JsonHelper.DeserializeFileToObject<PatientInfo>(path);

        

        try
        {
            ECGConversion.aECG.aECGFormat aecg = new ECGConversion.aECG.aECGFormat();
            ECGConversion.aECG.aECGComponent  aComponet= new ECGConversion.aECG.aECGComponent();
                
            ECGConversion.aECG.aECGSeries aecgSeries = new ECGConversion.aECG.aECGSeries();


            aComponet.SetSeries ( aecgSeries);
            aecg.Component = aComponet;
           //ECGConversion.aECG.aECGSeries aecgseries1 = new ECGConversion.aECG.aECGSeries();
  
             IECGFormat CurrentECG = null;
          //  CurrentECG = aecg;

            UnknownECGReader _ECGReader = null;
            if (true)
            {
                int index = 0;
                if (_ECGReader == null)
                    _ECGReader = new UnknownECGReader();
                CurrentECG = _ECGReader.Read("Example.xml");
                //
                //需要在此处 给 CurrentECG  赋值 
                //读取 json文件中的 数据，赋值CurrentECG
                int leadCount = patientInfo.ChDatas.Count;
                Signal[] _sign = new Signal[leadCount];
                for (int i = 0; i < leadCount; i++)
                {
                    _sign[i] = new Signal();

                    try
                    {
                        string leadname = patientInfo.ChDatas[i].LeadName.Trim();

                        // 导联类型
                        _sign[i].Type = (LeadType)(LeadTypeVitalRefId)ECGConverter.EnumParse(
                             typeof(LeadTypeVitalRefId), leadname, true);
                        //导联数据 ，
                        string[] datastr = patientInfo.ChDatas[i].digital.TrimEnd().Split(' ');


                        short[] shortArray = Array.ConvertAll<string, short>(datastr, delegate(string s) { return (short)(float.Parse(s) * 10000); });
                        _sign[i].Rhythm = (short[])shortArray.Clone();
                        _sign[i].RhythmStart = 0;
                        _sign[i].RhythmEnd = shortArray.Length / 500;

                    }
                    catch (Exception ex)
                    {

                        throw;
                    }

                }

                Signals signals = new Signals();
                signals.SetLeads(_sign);
                CurrentECG.Signals.getSignals(out signals);

                //采样率
                signals.RhythmSamplesPerSecond = int.Parse(patientInfo.Increament);

                //增益 
                signals.RhythmAVM = int.Parse(patientInfo.ChDatas[1].Sacle);

                //在这里设置参数信息 
                //setLeadMeasurements
                //设置导联参数 
                //LeadMeasurements leadMeasurements;

                //CurrentECG.LeadMeasurements.getLeadMeasurements(out leadMeasurements);
                //这里补充参数
                //CurrentECG.LeadMeasurements.setLeadMeasurements(leadMeasurements);

                //setGlobalMeasurements 总分析参数
                ECGConversion.ECGGlobalMeasurements.GlobalMeasurements globalMeasurements = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);
                //ECGConversion.ECGGlobalMeasurements.GlobalMeasurements glob = new ECGConversion.ECGGlobalMeasurements.GlobalMeasurements();
                globalMeasurements.Pdur = 120;
                globalMeasurements.QTc = 220;
                //12个 导联的信息 
                //ECGConversion.ECGGlobalMeasurements. GlobalMeasurement[] gment=new ECGConversion.ECGGlobalMeasurements.GlobalMeasurement[12];
                // glob.measurment = gment;
                CurrentECG.GlobalMeasurements.setGlobalMeasurements(globalMeasurements);
                CurrentECG.GlobalMeasurements.getGlobalMeasurements(out globalMeasurements);

                ECGConversion.ECGDiagnostic.Statements stat;
                CurrentECG.Diagnostics.getDiagnosticStatements(out stat);

                int NrConfigItems = CurrentECG.Config.NrConfigItems;

                ECGConversion.aECG.aECGFormat eCGFormat = (ECGConversion.aECG.aECGFormat)CurrentECG;

                ECGConversion.aECG.aECGComponent aECGComponent = eCGFormat.Component;
                int apcount = aECGComponent.Count;
                ECGConversion.aECG.aECGSeries aecgseries = aECGComponent[0];
                 //获取滤波器 相关参数信息
                ECGConversion.aECG.aECGControlVariableHolder[] controlVaribleHolder = aecgseries.ControlVariables;
               Console.WriteLine("滤波器参数");
                foreach (var item in controlVaribleHolder)
                {
                    if (item != null)
                    {
                        Console.WriteLine(item.Code.Code + ":" + item.ControlVariable.InnerVariables[0].Code.Code + ":" + item.ControlVariable.InnerVariables[0].Value.Value);
                        foreach (var itemtemp in item.ControlVariable.InnerVariables)
                        {
                            if (itemtemp != null)
                            {
                                Console.WriteLine("--" + itemtemp.Code.Code + ":" + itemtemp.Value.Value + ":" + itemtemp.Value.Type);
                            }

                        }
                    }

                }
                //重新赋值



              //var varVariable = aecgseries.ControlVariables.Select(s=>s.ControlVariable!=null);
               ECGConversion.aECG.aECGControlVariable[] aECGControls = controlVaribleHolder[0].ControlVariable.InnerVariables;

               ECGConversion.aECG.aECGCode acode = controlVaribleHolder[0].Code;
              // controlVarible[0].ControlVariable.InnerVariables

             //  ECGConversion.aECG.aECGCode acode=aecgseries.Code;

              // ECGConversion.aECG.aECGValuePair 
              //设置 参数 controlVaribleHolder
             ECGConversion.aECG.aECGAnnotationSet[] aecgsets = aecgseries.Annotation;

             ECGConversion.aECG.aECGAnnotation[] aECGAnnotations = aecgsets[0].Annotation;

                    //var vapair = aECGAnnotations[1].Annotation[4].Value;

                    //ECGConversion.aECG.aECGCode vacode = aECGAnnotations[1].Annotation[4].Code;
                    //  vacode.Code = "";

                    //int count= aECGAnnotations[1].Annotation
                Console.WriteLine("获取其他参数");
                foreach (ECGConversion.aECG.aECGAnnotation item  in aECGAnnotations[0].Annotation)
                {
                        if (item!=null)
                        {
                            Console.WriteLine("Code"+item.Code + ":" + item.Code.Code + ":" + item.Code.DisplayName);
                            Console.WriteLine("Value" + item.Value.Code + ":" + item.Value.Type + ":" + item.Value.Value);

                            Console.WriteLine("aECGBoundary 参数");
                            //aECGBoundary 参数
                            ECGConversion.aECG.aECGBoundary[] eCGBoundaries = item.SupportingROI.Boundary;
                            foreach (var itembd in eCGBoundaries)
                            {
                                if (itembd!=null)
                                {
                                    ECGConversion.aECG.aECGValuePair pair1 = itembd.Value;
                                    if (pair1["low"] != null)
                                    {
                                        Console.WriteLine("pair1[low]--" + pair1["low"].Name + ":" + pair1["low"].Value + ":" + pair1["low"].Unit);
                                    }
                                    else if (pair1["high"] != null)
                                    {
                                        Console.WriteLine("pair1[high]--" + pair1["high"].Name + ":" + pair1["high"].Value + ":" + pair1["high"].Unit);
                                    }
                                    
                                }
                                
                            }
                            

                            //这里输出的
                            /* CodeECGConversion.aECG.aECGCode:MDC_ECG_WAVC:
                             ValueMDC_ECG_WAVC_PWAVE: CE: NaN
 CodeECGConversion.aECG.aECGCode:MDC_ECG_WAVC:
                             ValueMDC_ECG_WAVC_QRSWAVE: CE: NaN
 CodeECGConversion.aECG.aECGCode:MDC_ECG_WAVC:
                             ValueMDC_ECG_WAVC_TWAVE: CE: NaN
 CodeECGConversion.aECG.aECGCode:MDC_ECG_TIME_PD_P:
                             Value: PQ: 102
 CodeECGConversion.aECG.aECGCode:MDC_ECG_TIME_PD_PR:
                             Value: PQ: 148
 CodeECGConversion.aECG.aECGCode:MDC_ECG_TIME_PD_QRS:
                             Value: PQ: 120
 CodeECGConversion.aECG.aECGCode:MDC_ECG_TIME_PD_QT:
                             Value: PQ: 420
 CodeECGConversion.aECG.aECGCode:MDC_ECG_TIME_PD_QTc:
                             Value: PQ: 443
 CodeECGConversion.aECG.aECGCode:MDC_ECG_ANGLE_P_FRONT:
                             Value: PQ: 44
 CodeECGConversion.aECG.aECGCode:MDC_ECG_ANGLE_QRS_FRONT:
                             Value: PQ: -61
 CodeECGConversion.aECG.aECGCode:MDC_ECG_ANGLE_T_FRONT:
                             Value: PQ: 86*/
                        }
                }
                    //ECGConversion.aECG.aECGValuePair pair = new ECGConversion.aECG.aECGValuePair();
                    //pair.

           // var va = aECGAnnotations[1].Annotation[4].Value.Set();
            // 修改
            //for (int i = 0; i < aECGAnnotations[1].Annotation.Length; i++)
            //{
            //    if (aECGAnnotations[1].Annotation[i] != null)
            //    {
            //        aECGAnnotations[1].Annotation[i].Value.Empty();
            //        aECGAnnotations[1].Annotation[i].Code.Empty();
            //    }
            //}
            ECGConversion.aECG.aECGValuePair pair =new ECGConversion.aECG.aECGValuePair("value",344,"ms");
             pair.Type = "PQ";
              pair.Unit = "ms";
             ECGConversion.aECG.aECGAnnotation annotation = new ECGConversion.aECG.aECGAnnotation();
             annotation.Value = pair;

             ECGConversion.aECG.aECGSupportingROI supportingROI = new ECGConversion.aECG.aECGSupportingROI();

            // supportingROI.

             // pair.Set();
             //这里设置 患者信息
               CurrentECG.Demographics.FirstName = patientInfo.Name;
                //
                CurrentECG.Demographics.Gender = (ECGConversion.ECGDemographics.Sex)int.Parse(patientInfo.Sex);
                //身高
                ushort height = ushort.Parse(patientInfo.Height);
                CurrentECG.Demographics.setPatientHeight(height, ECGConversion.ECGDemographics.HeightDefinition.Millimeters);
                ushort weight = ushort.Parse(patientInfo.Weight);
                CurrentECG.Demographics.setPatientWeight(weight, ECGConversion.ECGDemographics.WeightDefinition.Kilogram);

                ushort age = ushort.Parse(patientInfo.Age);
                ECGConversion.ECGDemographics.AgeDefinition ageuint = ECGConversion.ECGDemographics.AgeDefinition.Unspecified;
                if (patientInfo.Ageuint == "岁")
                {
                    ageuint = ECGConversion.ECGDemographics.AgeDefinition.Years;
                }
                else if (patientInfo.Ageuint == "月")
                {
                    ageuint = ECGConversion.ECGDemographics.AgeDefinition.Months;
                }
                else if (patientInfo.Ageuint == "天")
                {
                    ageuint = ECGConversion.ECGDemographics.AgeDefinition.Days;
                }
                else if (patientInfo.Ageuint == "周")
                {
                    ageuint = ECGConversion.ECGDemographics.AgeDefinition.Weeks;
                }
                CurrentECG.Demographics.setPatientAge(age, ageuint);


                IECGFormat writeFile = CurrentECG;

                if (index >= 0)
                {
                    ECGConfig cfg1 = ECGConverter.Instance.getConfig(index);

                    if (cfg1 != null)
                    {
                        cfg1["Lead Format"] = "Regular";
                        cfg1["Gain"] = "10";
                    }

                    try
                    {
                        if (CurrentECG.GetType() != ECGConverter.Instance.getType(index))
                        {
                            if (((ECGConverter.Instance.Convert(CurrentECG, index, cfg1, out writeFile) != 0)
                            || !writeFile.Works())
                            && (writeFile != null))
                            {
                                writeFile.Dispose();
                                writeFile = null;
                            }
                        }
                    }
                    catch
                    {
                        if (writeFile != null)
                        {
                            writeFile.Dispose();
                            writeFile = null;
                        }
                    }

                    if (writeFile == null)
                    {
                        //MessageBox.Show(this, "Converting of file has failed!", "Converting failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                ECGWriter.Write(writeFile, "test.xml", true);

                if (writeFile != CurrentECG)
                    writeFile.Dispose();

                if (ECGWriter.getLastError() != 0)
                {
                    //MessageBox.Show(this, ECGWriter.getLastErrorMessage(), "Writing of file failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        catch (Exception ex)
        {
            //MessageBox.Show(this, ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    static void Main3(string[] args)
    {
        Console.WriteLine("aheeefd");
        string iput=Console.ReadLine();
        Console.WriteLine("输入：" + iput);
    }
    }
}
